<template>
  <div class="app-container">

    <h2 class="steps-title">发布新课程</h2>

    <el-steps :active="active" finish-status="success" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="发布课程"/>
    </el-steps>

    <!-- 课程信息表单 -->
    <el-form label-width="120px"
             :model="courseInfo"
             ref="courseInfoForm"
             status-icon
             :rules="courseInfoRules">

      <el-form-item label="课程标题" prop="name">
        <el-input maxlength="100"
                  autocomplete="off"
                  show-word-limit
                  v-model="courseInfo.name"
                  placeholder="示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"
                  style="width: 85%"/>
      </el-form-item>

      <!-- 所属分类 -->
      <el-form-item label="课程类别" prop="category">
        <!-- 一级分类 -->
        <el-select
          style="width: 180px"
          v-model="courseInfo.categoryParentId"
          @change="categoryParentChanged"
          placeholder="请选择一级分类">
          <el-option
            v-for="category in categoryNestedList"
            :key="category.id"
            :label="category.name"
            :value="category.id"/>
        </el-select>

        <!-- 二级分类 -->
        <el-select
          style="width: 180px"
          v-model="courseInfo.categoryId"
          placeholder="请选择二级分类">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="总课时" prop="lessonSum">
        <el-input-number
          :min="1"
          :max="999"
          v-model="courseInfo.lessonSum"
          placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <el-form-item label="课程价格" prop="price">
        <el-input-number
          :min="0"
          :max="9999"
          v-model="courseInfo.price"
          placeholder="免费课程请设置为0元"/>&nbsp;&nbsp;&nbsp;&nbsp;元
      </el-form-item>

      <el-form-item label="课程级别" prop="level">
        <el-select v-model="courseInfo.level" placeholder="请选择课程级别" style="width: 180px">
          <el-option
            v-for="item in levels"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 课程简介 -->
      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面 -->
      <el-form-item label="课程封面">
        <span style="font-size: 15px">点击图片上传封面，否则将使用所示默认封面。只能上传 JPG 或 PNG 格式图片，且大小不超过2MB</span>
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          accept=".jpg,.png"
          :before-upload="beforeAvatarUpload"
          :action="BASE_API +'/oss/teacher/file/upload?host=cover'"
          class="cover-uploader">
          <img :src="courseInfo.cover" width="500px" style="max-height: 300px;object-fit: cover;">
        </el-upload>
      </el-form-item>

    </el-form>

    <div style="text-align:center">
      <el-button :disabled="saveBtnDisabled" type="primary" @click="next()">保存并下一步</el-button>
    </div>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { saveCourse, getCourseById, updateCourseById } from '@/api/course'
  import { getCategoryNestedList } from '@/api/category'
  import Tinymce from '@/components/Tinymce'
  import { validNormal } from '@/utils/validate'

  const defaultForm = {
    name: '',
    courseId: '',
    categoryId: '',
    categoryParentId: '',
    teacherId: '',
    lessonSum: 0,
    buySum: 0,
    level: 0,
    description: '',
    level: 0,
    cover: process.env.VUE_APP_OSS_PATH + '/cover/default.jpg',
    price: 0
  }

  export default {
    components:{
      Tinymce
    },
    data() {
      //检验标题
      const validateName = (rule, value, callback) => {
        if (value.length < 5 || value > 100 || !validNormal(value)){
          callback(new Error("请输入正确的课程标题，长度要求为5-100，且不能输入特殊字符"))
        }
        else callback()
      }

      //检验分类
      const validateCategory = (rule, value, callback) => {
        if (this.courseInfo.categoryId.length < 19 || this.courseInfo.categoryParentId.length < 19){
          callback(new Error("请选择课程分类"))
        }
        callback()
      }

      return {
        active: 0,
        courseInfo: defaultForm,
        saveBtnDisabled: false, // 保存按钮是否禁用
        categoryNestedList: [], // 一级分类列表
        categoryList: [], //二级分类列表
        BASE_API: process.env.VUE_APP_BASE_API,  //后端api地址
        //课程级别
        levels: [
          {value: 0, label :"入门"}, {value: 1, label: "初级"},
          {value: 2, label: "中级"}, {value: 3, label: "高级"}
        ],
        //检验规则
        courseInfoRules:{
          name:[{validator: validateName,trigger: 'blur'}],
          category:[{validator: validateCategory,trigger: ['blur','change'],type:'number'}],
        }
      }
    },

    watch: {
      $route(to, from) {
        this.init()
      }
    },

    computed: {
      ...mapGetters([
        'id',
        'name'
      ])
    },

    created() {
      this.init()
    },

    methods: {
      init() {
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          this.fetchCourseInfoById(id)
        } else {
          this.initCategoryNestedList()
          this.courseInfo = { ...defaultForm }
        }
        this.courseInfo.teacherId = this.id
      },

      //获取课程分类嵌套列表
      initCategoryNestedList(){
        getCategoryNestedList().then(result => {
          this.categoryNestedList = result.data.items
        })
      },

      //课程下拉框联动
      categoryParentChanged(value) {
        // console.log(value)
        for (let i = 0; i < this.categoryNestedList.length; i++) {
          if (this.categoryNestedList[i].id === value) {
            this.categoryList = this.categoryNestedList[i].children
            this.courseInfo.categoryId = ''
          }
        }
      },

      next() {
        this.$refs.courseInfoForm.validate((valid) => {
          if (valid) {
            //检验通过
            this.saveBtnDisabled = true
            if (!this.courseInfo.courseId) {
              this.saveData()
            } else {
              this.updateData()
            }
          }
          else {
            this.$message.error("请正确填写课程基本信息！")
            return false;
          }
        })
      },

      // 保存
      saveData() {
        saveCourse(this.$qs.stringify(this.courseInfo)).then(result => {
          this.$message({
            type: 'success',
            message: '保存成功！'
          })
          return result // 将响应结果传递给then
        }).then(result => {
          this.$router.push({ path: '/manage/course/chapter/' + result.data.courseId })
        })
      },

      updateData() {
        this.saveBtnDisabled = true
        updateCourseById(this.$qs.stringify(this.courseInfo)).then(result => {
          this.$message({
            type: 'success',
            message: '修改成功！'
          })
        })
        .then( () =>{
          this.$router.push({ path: '/manage/course/chapter/'+ this.courseInfo.courseId })
        })
      },


      //根据id获取课程信息
      fetchCourseInfoById(id) {
        getCourseById(id).then(result => {
          this.courseInfo = result.data.item

          getCategoryNestedList().then(result => {
            this.categoryNestedList = result.data.items
            // 填充二级菜单：遍历一级菜单列表
            for (let i = 0; i < this.categoryNestedList.length; i++){
              if (this.categoryNestedList[i].id === this.courseInfo.categoryParentId){
                this.categoryList = this.categoryNestedList[i].children
              }
            }
          })
        })
      },

      // 课程封面上传成功回调
      handleAvatarSuccess(res, file) {
        //console.log(res)// 上传响应
        //console.log(URL.createObjectURL(file.raw))// base64编码
        this.courseInfo.cover = res.data.item.url
        this.$message({
          type: 'success',
          message: '上传成功！'
        })
      },

      // 课程封面上传前检查
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isPIC = (isJPG || isPNG)

        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isPIC) {
          this.$message.error('上传封面图片只能是 JPG 或 PNG 格式！')
        }
        if (!isLt2M) {
          this.$message.error('上传封面图片大小不能超过 2MB！')
        }
        return isJPG && isLt2M
      }
    }
  }
</script>

<style scoped>
  .steps-title{
    padding: 20px;
    text-align: center;
  }
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
  .cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .cover-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
